﻿
using DataCollection.Infrastructure;
using DataCollection.WinForm.ViewModel;

namespace DataCollection.WinForm.Forms
{
    public partial class EditDeviceForm : DCBaseForm
    {
        #region 属性

        public string number = string.Empty;

        private DeviceViewModel viewModel = null!;

        /// <summary>
        /// 需要绑定的控件
        /// </summary>
        private Dictionary<string, Control> ControlDict = new Dictionary<string, Control>();

        #endregion

        #region 自定义方法

        #endregion

        #region 系统事件
        public EditDeviceForm()
        {
            InitializeComponent();
            Header.Text = "编辑设备";
            foreach (string name in Singleton.Instance.SerialPortList)
            {
                PortAddressSelect.Items.Add(name);
            }
            ControlDict.Add("number", DeviceNumberInput);
            ControlDict.Add("portAddress", PortAddressSelect);
            ControlDict.Add("baudrate", BaudrateSelect);
            ControlDict.Add("name", DeviceNameInput);
            ControlDict.Add("slaveAddress", SlaveAddressInput);
            ControlDict.Add("enable", DeviceStateSelect);
            ControlDict.Add("holdingRegisterCount", HRCountInput);
            ControlDict.Add("inputRegisterCount", IRCountInput);
            ControlDict.Add("coilStatusCount", DOCountInput);
            ControlDict.Add("inputStatusCount", DICountInput);
        }

        private void EditDeviceForm_Load(object sender, EventArgs e)
        {
            viewModel = new DeviceViewModel(long.Parse(number));
            foreach (var item in ControlDict)
            {
                Bindings(item.Value, "Text", item.Key, viewModel);
            }
        }
        private void ConfirmButton_Click(object sender, EventArgs e)
        {
            viewModel.Apply();
            Response response = viewModel.Update();
            if (response.Code == Response.SuccessCode)
            {
                if (this.Owner != null)
                {
                    ManageDeviceForm frm = (ManageDeviceForm)this.Owner;
                    frm.LoadDeviceList();
                    frm.Success(string.Format("【{0}】编辑成功", viewModel.Name));
                }
                this.Close();
            }
            else
            {
                Error(response.Msg);
            }
        }
        #endregion
    }
}
